/*
 * main.cpp
 *
 *  Created on: 19/04/2012
 *      Author: alex
 */

#include "application/Floor.h"

using namespace std;
#include <iostream>
#include <string.h>
#include <list>
#include <signal.h>
#include <assert.h>
#include <sys/wait.h>

#include "IPC/EventHandler.h"
#include "IPC/SignalHandler.h"
#include "IPC/NamedPipe.h"
#include "IPC/AnonymousPipe.h"
#include "application/Elevator.h"
#include "common/Argv.h"
#include "common/StringUtils.h"

class SIGINT_Handler : public EventHandler
{
    private:
        Elevator *m_elevator;
    public:

        SIGINT_Handler ():m_elevator(NULL)
        {
        }

        virtual int handleSignal ( int signum )
        {
            assert ( signum == SIGINT );

            if(m_elevator)
            	m_elevator->stopSimulation();

            return 0;
        }

        void setElevator(Elevator *elevator)
        {
            m_elevator = elevator;
        }

};

int main (int argc,char **argv)
{
	SIGINT_Handler sigintHandler;
	Argv arguments;

	arguments.setArgv(argv);

	int floorAmount = StringUtils:: StringToNumber<int>(arguments.getArg(1));
	float elevatorSpeed = StringUtils:: StringToNumber<float>(arguments.getArg(2));
	float elevatorMaxCapacity = StringUtils:: StringToNumber<float>(arguments.getArg(3));
	int elevatorId = StringUtils:: StringToNumber<int>(arguments.getArg(4));
	std::string floorProxyBasePath = arguments.getArg(5);
	std::string keyGenerationPath = arguments.getArg(6);
	int logLevel =LogLevelEnum::DEBUG;


	CLogger::create("Elevator "+arguments.getArg(4));
	CLogger::setLevel(logLevel);
	CLogger::log("Elevator started.",LogLevelEnum::DEBUG);

	Elevator *elevator = new Elevator(elevatorSpeed,elevatorMaxCapacity,0,floorAmount,floorProxyBasePath,elevatorId,keyGenerationPath);

	sigintHandler.setElevator(elevator);

    //Registro los event handlers
    SignalHandler :: getInstance()->registerHandler ( SIGINT,&sigintHandler );

	elevator->startSimulation();

    CLogger::log("Elevator terminated",LogLevelEnum::DEBUG);

    CLogger::destroy();
}
